package com.forum.demo.controller;

import com.forum.demo.common.AppResult;
import com.forum.demo.common.ResultCode;
import com.forum.demo.config.AppConfig;
import com.forum.demo.model.Article;
import com.forum.demo.model.ArticleReply;
import com.forum.demo.model.UserInfo;
import com.forum.demo.model.response.ArticleReplyResponse;
import com.forum.demo.services.IArticleReplyService;
import com.forum.demo.services.IArticleService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IArticleReplyService articleReplyService;

    @PostMapping("/create")
    public AppResult create(HttpServletRequest request, @NonNull Long articleId, @NonNull String content) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户状态
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 获取要回复的帖子对象
        Article article = articleService.selectById(articleId);
        // 是否存在，或已删除
        if (article == null || article.getDeleteState() == 1) {
            // 表示已删除或不存在
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 是否封帖
        if (article.getState() == 1) {
            // 表示已封贴
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        ArticleReply articleReply = new ArticleReply();
        articleReply.setContent(content);
        articleReply.setArticleId(articleId); // 要回复的帖Id
        articleReply.setPostUserId(user.getId()); // 回复的发送者
        articleReply.setContent(content); // 回复的内容
        // 写入回复
        articleReplyService.create(articleReply);
        return AppResult.success();
    }

    @GetMapping("/getReplies")
    public AppResult<List<ArticleReplyResponse>> getRepliesByArticleId(@NonNull Long articleId) {
        // 获取要回复的帖子对象
        Article article = articleService.selectById(articleId);
        // 是否存在，或已删除
        if (article == null || article.getDeleteState() == 1) {
            // 表示已删除或不存在
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        List<ArticleReplyResponse> articleReplys = articleReplyService.selectByArticleId(articleId);
        return AppResult.success(articleReplys);

    }
}
